package com.hyg.lib_music.ui.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.ContentObserver;
import android.graphics.Paint;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;

import com.hyg.lib_base.mainUtils.StatusBarUtil;
import com.hyg.lib_common.Base.BaseActivity;
import com.hyg.lib_common.DataModel.Music.Music;
import com.hyg.lib_common.Net.CommonHttpUtil;
import com.hyg.lib_music.R;
import com.hyg.lib_music.databinding.ActivityMusicPlayingDetailBinding;
import com.hyg.lib_music.service.MusicService;

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.ArrayList;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class MusicPlayingDetailActivity extends BaseActivity {
    ActivityMusicPlayingDetailBinding binding;
    String title;
    MusicService.OnStateChangeListenr listenr;
    String result = "";

    SettingsContentObserver mSettingsContentObserver;
    SeekBar sb_voice;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMusicPlayingDetailBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        init();
    }

    public void init() {
        StatusBarUtil.setStatusBar(3, this, getResources().getColor(R.color.white), 60, null, null, false);
        StatusBarUtil.setDarkMode(this);

        binding.tvResultShow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (binding.rlShowResult.getVisibility() == View.VISIBLE) {
                    binding.rlShowResult.setVisibility(View.GONE);
                } else {
                    binding.rlShowResult.setVisibility(View.VISIBLE);
                }
            }
        });
        binding.back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
                overridePendingTransition(0, R.anim.out_from_top);
            }
        });

        binding.ivMusicMenu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MusicPlayingDetailActivity.this, PlayingListActivity.class);
                intent.putParcelableArrayListExtra("data", (ArrayList<? extends Parcelable>) MusicMainActivity.serviceBinder.getPlayingList());
                startActivity(intent);
            }
        });


        Music currentMusic = MusicMainActivity.serviceBinder.getCurrentMusic();
        if (MusicMainActivity.serviceBinder.isPlaying()) {
            binding.ivMusicPlay.setImageResource(R.mipmap.new_music_detail_pause);
        } else {
            binding.ivMusicPlay.setImageResource(R.mipmap.new_music_detail_play);
        }
        String name = getNameString(currentMusic);
        binding.tvMusicName.setText(name);
        binding.ivNewPlayFav.setCHecked(currentMusic.isFav);
        String title_tv = "音乐";
        switch (currentMusic.parentType) {
            case 0:
                title_tv = "音乐";
                break;
            case 1:
                title_tv = "养生定制方案";
                break;
            case 2:
                title_tv = "助眠定制方案";
                break;
            case 3:
                title_tv = "解压定制方案";
                break;
        }
        binding.tvTitle.setText(title_tv);
        if (TextUtils.isEmpty(currentMusic.testResult)) {
            binding.tvResultShow.setVisibility(View.GONE);
            binding.rlShowResult.setVisibility(View.GONE);
        } else {
            binding.tvResultShow.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
            binding.tvResultName.setText(currentMusic.testResult);
        }
        listenr = new MusicService.OnStateChangeListenr() {
            @Override
            public void onPlayProgressChange(long played, long duration) {
                binding.prbMusicProgress.setProgress((int) (played * 100.00 / duration));
            }

            @Override
            public void onPlay(Music item) {
                binding.ivMusicPlay.setImageResource(R.mipmap.new_music_detail_pause);
                binding.tvMusicName.setText(getNameString(item));
                binding.ivNewPlayFav.setCHecked(currentMusic.isFav);

                String title_tv = "音乐";
                switch (item.parentType) {
                    case 0:
                        title_tv = "音乐";
                        break;
                    case 1:
                        title_tv = "养生定制方案";
                        break;
                    case 2:
                        title_tv = "助眠定制方案";
                        break;
                    case 3:
                        title_tv = "解压定制方案";
                        break;
                }
                binding.tvTitle.setText(title_tv);
                if (TextUtils.isEmpty(item.testResult)) {
                    binding.tvResultShow.setVisibility(View.GONE);
                    binding.rlShowResult.setVisibility(View.GONE);
                } else {
                    binding.tvResultShow.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
                    binding.tvResultName.setText(item.testResult);
                }
                Log.i("lgb", "onPlay:isfav= " + currentMusic.isFav);
            }

            @Override
            public void onPause() {
                binding.ivMusicPlay.setImageResource(R.mipmap.new_music_detail_play);
            }
        };
        MusicMainActivity.serviceBinder.registerOnStateChangeListener(listenr);
        binding.ivMusicPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MusicMainActivity.serviceBinder.playOrPause();
            }
        });

        binding.ivNewPlayNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MusicMainActivity.serviceBinder.playNext();
            }
        });

        binding.ivMusicPre.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MusicMainActivity.serviceBinder.playPre();
            }
        });
        binding.ivNewPlayFav.setData(currentMusic.id);
        binding.ivNewPlayHint.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showBottomDialog();
            }
        });
        registerVolumeChangeReceiver();
    }


    private String getNameString(Music currentMusic) {
        String name = currentMusic.musicName;
        if (!TextUtils.isEmpty(currentMusic.musician) && !currentMusic.musician.equalsIgnoreCase("无")) {
            name += "-" + currentMusic.musician;
        }
        return name;
    }


    private void showBottomDialog() {
        Dialog bottomDialog = new Dialog(this, R.style.BottomDialog);
        View contentView = LayoutInflater.from(this).inflate(R.layout.dialog_music_bottom, null);
        ImageView iv_clock = contentView.findViewById(R.id.iv_clock);
        SeekBar sb_shock = contentView.findViewById(R.id.sb_shock);
        sb_voice = contentView.findViewById(R.id.sb_voice);
        Button btn_cancel = contentView.findViewById(R.id.btn_cancel);
        iv_clock.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MusicPlayingDetailActivity.this, ClockSettingActivity.class));
            }
        });
        getVoiceNumber(sb_voice, sb_shock);
        btn_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomDialog.dismiss();
            }
        });
        bottomDialog.setContentView(contentView);
        ViewGroup.LayoutParams layoutParams = contentView.getLayoutParams();
        layoutParams.width = getResources().getDisplayMetrics().widthPixels;
        contentView.setLayoutParams(layoutParams);
        bottomDialog.getWindow().setGravity(Gravity.BOTTOM);
        bottomDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation);
        bottomDialog.show();
    }


    public void getVoiceNumber(SeekBar sb_voice, SeekBar sb_shock) {
        AudioManager am = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
        //获取系统最大音量
        int maxVolume = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        sb_voice.setMax(maxVolume);
        sb_shock.setMax(1000);
//        seekBar_high_frequency.setMax(1000);
        //获取当前音量
        int currentVolume = am.getStreamVolume(AudioManager.STREAM_MUSIC);
        sb_voice.setProgress(currentVolume);
        sb_voice.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {
                    //设置系统音量
                    am.setStreamVolume(AudioManager.STREAM_MUSIC, progress, 0);
                    int currentVolume = am.getStreamVolume(AudioManager.STREAM_MUSIC);
                    seekBar.setProgress(currentVolume);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });

        sb_shock.setOnSeekBarChangeListener(new SeekBar
                .OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar
                    , int progress, boolean fromUser) {
                // 设置重低音的强度
                MusicMainActivity.serviceBinder.setStrength((short) progress);
                // 设置普通低音的强度
                MusicMainActivity.serviceBinder.UpdateSetEqualizer(progress, false);
                editorn = mc.edit();
                editorn.putInt("BassProgress", progress);
                editorn.commit();
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });

        //获得当前低音
//        sb_shock.setProgress(serviceBinder.getStrength());
        //设置当前
        sb_shock.setProgress(mc.getInt("BassProgress", 500));
//       seekBar_high_frequency.setProgress(mc.getInt("HighProgress", 500));
    }


    private void registerVolumeChangeReceiver() {
        mSettingsContentObserver = new SettingsContentObserver(this, new Handler());
        getApplicationContext().getContentResolver().registerContentObserver(android.provider.Settings.System.CONTENT_URI, true, mSettingsContentObserver);
    }

    private void unregisterVolumeChangeReceiver() {
        getApplicationContext().getContentResolver().unregisterContentObserver(mSettingsContentObserver);
    }

    public class SettingsContentObserver extends ContentObserver {
        Context context;

        public SettingsContentObserver(Context c, Handler handler) {
            super(handler);
            context = c;
        }

        @Override
        public boolean deliverSelfNotifications() {
            return super.deliverSelfNotifications();
        }

        @Override
        public void onChange(boolean selfChange) {
            super.onChange(selfChange);
            if (sb_voice != null) {
                AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
                int currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
//            System.out.println("currVolume:" + currentVolume);
                sb_voice.setProgress(currentVolume);
            }
        }
    }


    @Override
    public void finish() {
        super.finish();
        unregisterVolumeChangeReceiver();
    }
}